<?php

  function saveNewUser(&$db, $username) {
    $insertResult = $db->dbInsert("INSERT INTO lobbyusers (`id`, `username`, `lastactive`, `loggedon`, `ip`, `posts`) VALUES (NULL, '$username', '".date('Y-m-d H:i:s')."', '1', '".$_SERVER['REMOTE_ADDR']."', '0')");
  }

  function postMessage($db, $user, $message, $posted) {
    $postSql = "INSERT INTO lobby (`id`, `username`, `message`, `posted`) VALUES 
      (NULL, '".mysql_real_escape_string($user)."', '".mysql_real_escape_string($message)."', '$posted')";
    $db->dbInsert($postSql);
    if ($user != "system") {
      $db->dbUpdate("UPDATE lobbyusers SET `posts`=`posts`+1 WHERE `username`='$user';");
    }
  }

  function displayProgress($value) {
    if ((int)$value == 1) {
      return "True";
    } else {
      return "False";
    }
  }

  function displayJoinLink($gameId) {
    return '<a href="index.php?joingame='.$gameId.'">Join</a>';
  }

  function removePlayerFromGames($db, $username) {
    $result = $db->dbSelect("SELECT * FROM games WHERE player1='$username' OR player2='$username' OR player3='$username' OR player4='$username'");
    
    if ($result) {
      while ($gameDetails = mysql_fetch_array($result)) {
        if ($gameDetails['player1'] == $username) {
          clearGamePlayer($db, 'player1', $gameDetails['id']);
        } else if ($gameDetails['player2'] == $username) {
          clearGamePlayer($db, 'player2', $gameDetails['id']);
        } if ($gameDetails['player3'] == $username) {
          clearGamePlayer($db, 'player3', $gameDetails['id']);
        } if ($gameDetails['player4'] == $username) {
          clearGamePlayer($db, 'player4', $gameDetails['id']);
        }
      }
    }
  }
  
  function clearGamePlayer($db, $column, $gameId) {
    debug("Clear $column of game Id $gameId");
    $db->dbUpdate("UPDATE games SET `$column`='-' WHERE id='".$gameId."'");
  }




?>
